<template>
  <div>
    <div class="step-wrap">
      <el-steps :space="200" :active="active" finish-status="success" align-center v-if="form.isPublish === '0'">
        <el-step title="创建MR"></el-step>
        <el-step title="合并代码"></el-step>
        <el-step title="打测试tag"></el-step>
      </el-steps>
      <el-steps :space="200" :active="active" finish-status="success" align-center v-else>
        <el-step title="合并master"></el-step>
        <el-step title="创建MR"></el-step>
        <el-step title="合并代码"></el-step>
        <el-step title="打测试tag"></el-step>
      </el-steps>
    </div>
    <div class="form-wrap">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="工程" prop="project">
          {{ form.project }}
          <el-select v-model="form.project">
            <el-option v-for="item in projectsOptions" :key="item.value" :value="item.value" :label="item.label"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="版本号" prop="version">
          <el-select v-model="form.version">
            <el-option v-for="item in branchsOptions" :key="item.value" :value="item.value" :label="item.label"> </el-option>
          </el-select>
        </el-form-item>
          <el-form-item label="合并" prop="test">
          test
        </el-form-item>
        <el-form-item label="有版本发布" prop="isPublish">
          <el-radio v-model="form.isPublish" label="1">是</el-radio>
          <el-radio v-model="form.isPublish" label="0">否</el-radio>
        </el-form-item>
        <el-form-item label="上一次发布的版本号" prop="prePublishVersion" v-if="form.isPublish !== '1'">
          <el-select v-model="form.prePublishVersion">
            <el-option v-for="item in branchsOptions" :key="item.value" :value="item.value" :label="item.label"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合并到master的分支" prop="preMergeVersion" v-if="form.isPublish !== '1'">
          {{ preMergeVersion }}
        </el-form-item>
      </el-form>
      <div v-if="testBranchName" style="margin-top: 20px; color: red; font-weight: 700">测试分支：{{ testBranchName }}</div>
    </div>

    <div style="margin-top: 20px; color: red; font-weight: 700">测试分支：{{ testBranchName }}</div>
    <el-form-item>
      <el-button type="primary" @click="onPubilshTest" :loading="isLoading">打包测试版</el-button>
      <!-- 在打包正式版的时候不能合并master，合并master操作一定是在打包测试版的时候进行的 -->
      <!-- <el-tooltip class="item" effect="dark" placement="right">
                        <div slot="content" style="line-height: 22px">
                            <p>发布分支是在最大的测试分支号的基础上打tag，如果不是请手动处理</p>
                            <p>例如：当前分支有多个测试tag</p>
                            <p>hotfix_1.0.0.0_1, hotfix_1.0.0.0_2, hotfix_1.0.0.0_3</p>
                            <p>我们是根据hotfix_1.0.0.0_3打发布的tag，如果不是请手动处理</p>
                        </div> -->
      <el-button v-if="form.isPublish === '1'" disabled>打包正式版</el-button>
      <el-button type="primary" @click="onShowChecklist" v-else>打包正式版</el-button>
      <!-- </el-tooltip> -->
    </el-form-item>
     <el-dialog title="发布checklist" :visible.sync="checklistVisible" center>
      <!-- <el-checkbox-group v-model="checklist">
        <el-checkbox v-for="item in checklistOptions" :key="item.value" :label="item.value" style="color: red">{{ item.label }}</el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onPublish" :loading="isPublishLoading">确 定</el-button>
      </span> -->
    </el-dialog>
  </div>
</template>

<script setup>
import { findProjects, findBranchsByProject, createMergeRequest, acceptMergeRequest, findTagsByProject, createTagByProject, closeMergeRequest, removeTagByProject, findMergeRequest, findMergeRequestList,findCompareByProject ,findMergeRequestChanges} from './api/index.js'
import { ref, reactive, watch, onMounted, computed, toRaw } from 'vue'
import {ElMessage} from 'element-plus'
const form = ref({
  version: '',
  project: '',
  isPublish: '1', // 是否之前有版本发布
  testSetVersion: 'development_TestSet',
  isTestSet: '1',
  prePublishVersion: '',
})

const formRef = ref()
const checklistVisible = ref(false)
const isLoading = ref(false)
const isPublishLoading = ref(false)
const active = ref(0)
const testBranchName = ref('')
const projectsOptions = ref([]) // 项目列表
const branchsOptions = ref([]) // 分支列表
const rules = {
  project: [{ required: true, message: '请选择项目', trigger: 'change' }],
  version: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
  isPublish: [{ required: true, message: '请选择发布类型', trigger: 'change' }],
}

const versionNum = ref('dev_WH25.6.2_1')

const checklistOptions = ref([
  { label: '请求前缀配置确认（api文件夹下面，config.js文件中production配置）', value: '1' },
  { label: 'Master分支已经合并到当前版本', value: '2' },
])

watch(
  () => form.value.project,
  v => {
    console.log('form', v)
    getBranchs(v)
  }
)

// 获取项目列表
const getProjects = async () => {
  const { data } = await findProjects()
  projectsOptions.value = data.map(item => ({
    label: item.name,
    value: item.id,
  }))
}

// 获取项目分支列表
const getBranchs = async projectId => {
  const { data } = await findBranchsByProject({
    projectId,
  })
  branchsOptions.value = data.map(item => {
    item.label = item.name + ` (${item.merged ? '已合并' : '未合并'})`
    item.value = item.name
    return item
  })
}

const onShowChecklist = () => {
  console.log('[ checklistVisible ]-136', 1111)

  checklistVisible.value = true
  this.checklist = []
}

const onPubilshTest = async () => {
  active.value = 0
  testBranchName.value = ''
  formRef.value.validate(async valid => {
    if (valid) {
      try {
        console.log('[ valid ]-146', valid)

        // if (form.value.isPublish === '1') {
        //   // 1. 最近有发布的情况下，检查master是否合并到了对应的feature分支
        //   const { data: masterMerge } = await createMergeRequest({
        //     projectId: form.value.project,
        //     source_branch: 'master',
        //     target_branch: form.value.version,
        //     title: 'merge request from master',
        //     description: `merge from master to ${form.value.version}`
        //   })
        //   if (masterMerge.changes_count) {
        //     await acceptMergeRequest({
        //       projectId: form.value.project,
        //       mrId: masterMerge.iid
        //     })
        //   } else {
        //     await closeMergeRequest({
        //       projectId: form.value.project,
        //       mrId: masterMerge.iid
        //     })
        //   }
        //   active.value++
        // }
        // 2. 建merge request
        // 合过master 直接打包
        // TODO  多版本 获取 目标 development 分支号 Testset
        // 默认 test1 分支
        const targetBranch = branchsOptions.value.filter(item => item.name.indexOf('test') === 0)
        if (targetBranch.length > 1) {
          ElMessage.error('匹配的development分支过多：' + targetBranch.length)
          isLoading.value = false
        } else if (targetBranch.length === 0) {
          ElMessage.error('没有找到对应的development分支！')
          isLoading.value = false
        } else {
          // merge request的title都会加上版本号，这里先查询有当前版本号的merge request，如果存在就不用创建merge request
          // merge request的命名规则：必须加版本号
          const { data: mergeRequests } = await findMergeRequest({
            projectId: form.value.project,
            search: versionNum.value,
          })
            console.log('[ mergeRequests ]-186', mergeRequests)

          let mergeId = ''
          if (mergeRequests.length <= 0) {
            // 如果merge request不遵守规则，这边还是会出现冲突的情况
            // 冲突手动去gitlab 修复
            // feature 合并到 development
            // 先判断2个分支存在差异
            const { data: compare } = await findCompareByProject({
              projectId: form.value.project,
              from_branch: form.value.version,
              to_branch: targetBranch[0].name,
            })
            if(compare.diffs.length>0||compare.commits.length>0){
              const { data: mrInfo } = await createMergeRequest({
                projectId: form.value.project,
                source_branch: form.value.version,
                target_branch: targetBranch[0].name,
                title: 'merge request ' + versionNum.value,
                description: `merge from ${form.value.version} to ${targetBranch[0].name}`,
              })
              mergeId = mrInfo.iid
              console.log('[ compare ]-199',compare, mrInfo)
              if (!mrInfo.changes_count) {
                ElMessage.warning('当前分支没有更新！')
                await closeMergeRequest({
                  projectId: form.value.project,
                  mrId: mrInfo.iid,
                })
                isLoading.value = false
                return
              }
            }else{
              ElMessage.warning('当前分支没有更新！')
              isLoading.value = false
              return
            }
           
            
            active.value++
          } else {
            // 存在merge request 直接合并
            mergeId = mergeRequests[0].iid
            // 通过deepseek 查看merge request 差异
            const {data:merData} = await findMergeRequestChanges({
              projectId: form.value.project,
              mrId: mergeId,
            })
                const deepSeekService = new DeepSeekService();
              console.log('[ merData ]-237', merData)

            active.value++
          }
          // 3. 合并操作
        const {data:merData} =   await acceptMergeRequest({
            projectId: form.value.project,
            mrId: mergeId,
          })
          active.value++


          // 4. 打tag
          // const { data: tags } = await findTagsByProject({
          //   projectId: form.value.project,
          // })
          // let maxTagNum = maxHotfixTag(tags)
          // console.log(maxTagNum)
          // await createTagByProject({
          //   projectId: form.value.project,
          //   tag_name: 'hotfix_' + versionNum.value + '_' + (maxTagNum * 1 + 1),
          //   ref: targetBranch[0].name,
          // })
          // 定义异步睡眠函数
          const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
          await sleep(1000)
          // active.value++
          if(merData.changes_count){
            ElMessage.success('合并成功！')
          }
          isLoading.value = false
        
          // TODO boss 项目 无需hotfix 直接 可以 feature => development=>developmrnt_Testset
          // testSetVersion developmrnt_Testset 分支
          var mergenId = ''
      
          // TODO 打完正常tags BOSS 端 再继续 development = 》development_Testset
          if (form.value.project === 148 && form.value.isTestSet === '1') {
            bossBranchName.value = form.value.testSetVersion
          } else {
            bossBranchName.value = ''
          }
        }
      } catch (e) {
        console.log('[ e ]-288', e)
        isLoading.value = false
      }
    } else {
      isLoading.value = false
    }
  })
}

onMounted(() => {
  getProjects()
})
</script>

<style lang="scss" scoped>
.el-checkbox + .el-checkbox {
  margin-top: 20px;
  margin-left: 0;
}
.el-checkbox {
  display: block;
}
.step-wrap {
  margin-bottom: 30px;
  padding: 10px;
}
// /deep/ .el-checkbox,
// .el-checkbox__input {
//   white-space: normal;
//   word-break: break-all;
// }
// /deep/ .el-checkbox__label {
//   display: inline;
// }
</style>
